<template>
  <view class="community-container">
    <!-- 顶部导航 -->
    <view class="community-header">
      <view class="header-tabs">
        <view 
          v-for="(tab, index) in tabs" 
          :key="index"
          class="tab-item"
          :class="{ active: currentTab === tab.id }"
          @click="switchTab(tab.id)"
        >
          <text class="tab-text">{{ tab.name }}</text>
        </view>
      </view>
      <view class="header-actions">
        <u-icon name="search" size="22" color="#666" @click="goToSearch"></u-icon>
      </view>
    </view>
    
    <!-- 话题推荐 -->
    <view v-if="currentTab === 'recommend'" class="topic-recommend">
      <scroll-view class="topic-scroll" scroll-x>
        <view class="topic-list">
          <view 
            v-for="(topic, index) in hotTopics" 
            :key="index"
            class="topic-item"
            @click="viewTopic(topic)"
          >
            <text class="topic-tag">#{{ topic.name }}</text>
            <text class="topic-count">{{ formatCount(topic.postCount) }}条讨论</text>
          </view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 内容列表 -->
    <scroll-view 
      class="post-list" 
      scroll-y 
      @scrolltolower="loadMore"
      @refresherrefresh="onRefresh"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
    >
      <view 
        v-for="(post, index) in postList" 
        :key="post.id"
        class="post-item"
        @click="viewPost(post)"
      >
        <!-- 用户信息 -->
        <view class="post-header">
          <view class="user-info">
            <u-avatar :src="post.authorAvatar" size="40"></u-avatar>
            <view class="user-details">
              <text class="user-name">{{ post.authorName }}</text>
              <text class="post-time">{{ formatTime(post.createdAt) }}</text>
            </view>
          </view>
          <view class="post-actions">
            <u-icon name="more-dot-fill" size="20" color="#999" @click.stop="showPostMenu(post)"></u-icon>
          </view>
        </view>
        
        <!-- 帖子内容 -->
        <view class="post-content">
          <text class="post-title" v-if="post.title">{{ post.title }}</text>
          <text class="post-text">{{ post.content }}</text>
          
          <!-- 话题标签 -->
          <view v-if="post.topics && post.topics.length > 0" class="post-topics">
            <text 
              v-for="(topic, idx) in post.topics" 
              :key="idx"
              class="topic-tag"
              @click.stop="viewTopic(topic)"
            >
              #{{ topic.name }}
            </text>
          </view>
          
          <!-- 图片网格 -->
          <view v-if="post.images && post.images.length > 0" class="post-images">
            <view 
              class="image-grid"
              :class="`grid-${Math.min(post.images.length, 9)}`"
            >
              <image 
                v-for="(image, idx) in post.images.slice(0, 9)" 
                :key="idx"
                class="post-image"
                :src="image"
                mode="aspectFill"
                @click.stop="previewImages(post.images, idx)"
                :lazy-load="true"
              ></image>
              <view v-if="post.images.length > 9" class="more-images">
                <text class="more-text">+{{ post.images.length - 9 }}</text>
              </view>
            </view>
          </view>
          
          <!-- 视频 -->
          <view v-if="post.video" class="post-video" @click.stop="playVideo(post.video)">
            <image class="video-cover" :src="post.video.cover" mode="aspectFill"></image>
            <view class="video-play-btn">
              <u-icon name="play-circle" size="40" color="white"></u-icon>
            </view>
            <view class="video-duration">
              <text class="duration-text">{{ formatDuration(post.video.duration) }}</text>
            </view>
          </view>
        </view>
        
        <!-- 互动统计 -->
        <view class="post-stats">
          <view class="stat-item" @click.stop="toggleLike(post)">
            <u-icon 
              :name="post.isLiked ? 'heart-fill' : 'heart'" 
              size="18" 
              :color="post.isLiked ? '#ff4757' : '#999'"
            ></u-icon>
            <text class="stat-text" :class="{ liked: post.isLiked }">{{ formatCount(post.likeCount) }}</text>
          </view>
          
          <view class="stat-item" @click.stop="showPostComments(post)">
            <u-icon name="chat" size="18" color="#999"></u-icon>
            <text class="stat-text">{{ formatCount(post.commentCount) }}</text>
          </view>
          
          <view class="stat-item" @click.stop="sharePost(post)">
            <u-icon name="share" size="18" color="#999"></u-icon>
            <text class="stat-text">分享</text>
          </view>
          
          <view class="stat-item" @click.stop="toggleFavorite(post)">
            <u-icon 
              :name="post.isFavorited ? 'star-fill' : 'star'" 
              size="18" 
              :color="post.isFavorited ? '#ffd700' : '#999'"
            ></u-icon>
            <text class="stat-text" :class="{ favorited: post.isFavorited }">收藏</text>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view v-if="loading" class="loading-more">
        <u-loading-icon></u-loading-icon>
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- 没有更多 -->
      <view v-if="noMore" class="no-more">
        <text class="no-more-text">没有更多内容了</text>
      </view>
    </scroll-view>
    
    <!-- 发布按钮 -->
    <view class="publish-btn" @click="goToPublish">
      <u-icon name="edit" size="24" color="white"></u-icon>
    </view>
    
    <!-- 帖子操作弹窗 -->
    <u-popup 
      v-model="showPostActions" 
      mode="bottom" 
      height="auto"
      border-radius="20"
      closeable
    >
      <view class="post-actions-popup" v-if="selectedPost">
        <view class="action-header">
          <text class="action-title">帖子操作</text>
        </view>
        <view class="action-list">
          <view class="action-item" @click="reportPost(selectedPost)">
            <u-icon name="warning" size="20" color="#ff4d4f"></u-icon>
            <text class="action-text">举报</text>
          </view>
          <view class="action-item" @click="blockUser(selectedPost)">
            <u-icon name="close-circle" size="20" color="#999"></u-icon>
            <text class="action-text">屏蔽用户</text>
          </view>
          <view class="action-item" @click="copyLink(selectedPost)">
            <u-icon name="link" size="20" color="#1890ff"></u-icon>
            <text class="action-text">复制链接</text>
          </view>
        </view>
      </view>
    </u-popup>
    
    <!-- 评论弹窗 -->
    <u-popup 
      v-model="showComments" 
      mode="bottom" 
      height="70%"
      border-radius="20"
      closeable
    >
      <view class="comments-popup" v-if="selectedPost">
        <view class="comments-header">
          <text class="comments-title">评论 {{ selectedPost.commentCount }}</text>
        </view>
        <scroll-view class="comments-list" scroll-y>
          <view 
            v-for="(comment, index) in commentList" 
            :key="comment.id"
            class="comment-item"
          >
            <image class="comment-avatar" :src="comment.authorAvatar" mode="aspectFill"></image>
            <view class="comment-content">
              <text class="comment-author">{{ comment.authorName }}</text>
              <text class="comment-text">{{ comment.content }}</text>
              <view class="comment-meta">
                <text class="comment-time">{{ formatTime(comment.createdAt) }}</text>
                <view class="comment-actions">
                  <view class="comment-action" @click="likeComment(comment)">
                    <u-icon 
                      :name="comment.isLiked ? 'heart-fill' : 'heart'" 
                      size="14" 
                      :color="comment.isLiked ? '#ff4d4f' : '#999'"
                    ></u-icon>
                    <text class="action-count">{{ comment.likeCount || '' }}</text>
                  </view>
                  <view class="comment-action" @click="replyComment(comment)">
                    <u-icon name="chat" size="14" color="#999"></u-icon>
                    <text class="action-text">回复</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
        <view class="comment-input-bar">
          <input 
            class="comment-input" 
            v-model="commentText" 
            placeholder="写评论..."
            @confirm="submitComment"
          />
          <button class="send-btn" @click="submitComment">发送</button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { get, post } from '@/utils/request';

// 帖子接口
interface Post {
  id: string;
  authorId: string;
  authorName: string;
  authorAvatar: string;
  title?: string;
  content: string;
  images?: string[];
  video?: {
    url: string;
    cover: string;
    duration: number;
  };
  topics?: Topic[];
  likeCount: number;
  commentCount: number;
  shareCount: number;
  isLiked: boolean;
  isFavorited: boolean;
  createdAt: string;
}

// 话题接口
interface Topic {
  id: string;
  name: string;
  postCount: number;
  followCount?: number;
}

// 标签页接口
interface Tab {
  id: string;
  name: string;
}

// 评论接口
interface Comment {
  id: string;
  authorId: string;
  authorName: string;
  authorAvatar: string;
  content: string;
  likeCount: number;
  isLiked: boolean;
  createdAt: string;
  replies?: Comment[];
}

@Component
export default class CommunityPage extends Vue {
  // 数据属性
  currentTab: string = 'recommend';
  postList: Post[] = [];
  hotTopics: Topic[] = [];
  
  loading: boolean = false;
  refreshing: boolean = false;
  noMore: boolean = false;
  page: number = 1;
  pageSize: number = 20;
  
  // 弹窗相关
  showPostActions: boolean = false;
  showComments: boolean = false;
  selectedPost: Post | null = null;
  
  // 评论相关
  commentList: Comment[] = [];
  commentText: string = '';
  commentLoading: boolean = false;
  
  tabs: Tab[] = [
    { id: 'recommend', name: '推荐' },
    { id: 'following', name: '关注' },
    { id: 'latest', name: '最新' },
    { id: 'hot', name: '热门' }
  ];
  
  // 生命周期
  onLoad() {
    this.loadHotTopics();
    this.loadPosts();
  }
  
  onShow() {
    this.refreshPosts();
  }
  
  onPullDownRefresh() {
    this.onRefresh();
  }
  
  onReachBottom() {
    this.loadMore();
  }
  
  // 方法
  
  /**
   * 加载热门话题
   */
  async loadHotTopics() {
    try {
      const response = await get('/community/hot-topics', {
        limit: 10
      });
      
      this.hotTopics = response.data.topics || [];
    } catch (error) {
      console.error('加载热门话题失败:', error);
      // 使用模拟数据
      this.hotTopics = this.getMockTopics();
    }
  }
  
  /**
   * 加载帖子列表
   */
  async loadPosts(isRefresh: boolean = false) {
    if (this.loading) return;
    
    this.loading = true;
    
    try {
      const response = await get('/community/posts', {
        type: this.currentTab,
        page: isRefresh ? 1 : this.page,
        pageSize: this.pageSize
      });
      
      const newPosts = response.data.posts || [];
      
      if (isRefresh) {
        this.postList = newPosts;
        this.page = 1;
        this.noMore = false;
      } else {
        this.postList = [...this.postList, ...newPosts];
      }
      
      // 检查是否还有更多数据
      if (newPosts.length < this.pageSize) {
        this.noMore = true;
      } else {
        this.page++;
      }
      
    } catch (error) {
      console.error('加载帖子失败:', error);
      
      // 使用模拟数据
      if (isRefresh || this.postList.length === 0) {
        this.postList = this.getMockPosts();
      }
      
      uni.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.loading = false;
      this.refreshing = false;
      uni.stopPullDownRefresh();
    }
  }
  
  /**
   * 刷新帖子
   */
  async refreshPosts() {
    this.refreshing = true;
    await this.loadPosts(true);
  }
  
  /**
   * 下拉刷新
   */
  onRefresh() {
    this.refreshPosts();
  }
  
  /**
   * 加载更多
   */
  loadMore() {
    if (!this.noMore && !this.loading) {
      this.loadPosts();
    }
  }
  
  /**
   * 切换标签页
   */
  switchTab(tabId: string) {
    if (this.currentTab === tabId) return;
    
    this.currentTab = tabId;
    this.page = 1;
    this.noMore = false;
    this.postList = [];
    
    this.loadPosts(true);
  }
  
  /**
   * 格式化数量
   */
  formatCount(count: number): string {
    if (count < 1000) {
      return count.toString();
    } else if (count < 10000) {
      return (count / 1000).toFixed(1) + 'k';
    } else {
      return (count / 10000).toFixed(1) + 'w';
    }
  }
  
  /**
   * 格式化时间
   */
  formatTime(dateString: string): string {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    
    if (diff < 60000) { // 1分钟内
      return '刚刚';
    } else if (diff < 3600000) { // 1小时内
      return Math.floor(diff / 60000) + '分钟前';
    } else if (diff < 86400000) { // 24小时内
      return Math.floor(diff / 3600000) + '小时前';
    } else if (diff < 604800000) { // 7天内
      return Math.floor(diff / 86400000) + '天前';
    } else {
      return date.toLocaleDateString();
    }
  }
  
  /**
   * 格式化时长
   */
  formatDuration(seconds: number): string {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
  }
  
  /**
   * 查看帖子详情
   */
  viewPost(post: Post) {
    uni.navigateTo({
      url: `/pages/community/detail?id=${post.id}`
    });
  }
  
  /**
   * 查看话题
   */
  viewTopic(topic: Topic) {
    uni.navigateTo({
      url: `/pages/community/topic?id=${topic.id}&name=${encodeURIComponent(topic.name)}`
    });
  }
  
  /**
   * 预览图片
   */
  previewImages(images: string[], current: number) {
    uni.previewImage({
      urls: images,
      current: current
    });
  }
  
  /**
   * 播放视频
   */
  playVideo(video: any) {
    uni.navigateTo({
      url: `/pages/video/player?url=${encodeURIComponent(video.url)}`
    });
  }
  
  /**
   * 切换点赞
   */
  async toggleLike(postItem: Post) {
    try {
      const response = await post('/community/like', {
        postId: postItem.id,
        action: postItem.isLiked ? 'unlike' : 'like'
      });
      
      postItem.isLiked = !postItem.isLiked;
      postItem.likeCount += postItem.isLiked ? 1 : -1;
      
      uni.showToast({
        title: postItem.isLiked ? '点赞成功' : '取消点赞',
        icon: 'success'
      });
    } catch (error) {
      console.error('点赞操作失败:', error);
      uni.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  }
  
  /**
   * 切换收藏
   */
  async toggleFavorite(postItem: Post) {
    try {
      const response = await post('/community/favorite', {
        postId: postItem.id,
        action: postItem.isFavorited ? 'unfavorite' : 'favorite'
      });
      
      postItem.isFavorited = !postItem.isFavorited;
      
      uni.showToast({
        title: postItem.isFavorited ? '收藏成功' : '取消收藏',
        icon: 'success'
      });
    } catch (error) {
      console.error('收藏操作失败:', error);
      uni.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  }
  
  /**
   * 分享帖子
   */
  sharePost(post: Post) {
    // #ifdef MP-WEIXIN
    uni.share({
      provider: 'weixin',
      scene: 'WXSceneSession',
      type: 0,
      href: `https://your-domain.com/community/post/${post.id}`,
      title: post.title || post.content.substring(0, 30) + '...',
      summary: post.content,
      imageUrl: post.images && post.images.length > 0 ? post.images[0] : '/static/share-logo.png'
    });
    // #endif
    
    // #ifdef APP-PLUS || H5
    uni.showActionSheet({
      itemList: ['复制链接', '分享到微信', '分享到朋友圈'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            // 复制链接
            uni.setClipboardData({
              data: `https://your-domain.com/community/post/${post.id}`,
              success: () => {
                uni.showToast({
                  title: '链接已复制',
                  icon: 'success'
                });
              }
            });
            break;
        }
      }
    });
    // #endif
  }
  
  /**
   * 显示帖子菜单
   */
  showPostMenu(post: Post) {
    const itemList = ['举报', '不感兴趣'];
    
    // 如果是自己的帖子，添加删除选项
    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo && userInfo.id === post.authorId) {
      itemList.unshift('删除');
    }
    
    uni.showActionSheet({
      itemList,
      success: (res) => {
        const action = itemList[res.tapIndex];
        this.handlePostAction(post, action);
      }
    });
  }
  
  /**
   * 处理帖子操作
   */
  async handlePostAction(postItem: Post, action: string) {
    switch (action) {
      case '删除':
        uni.showModal({
          title: '确认删除',
          content: '确定要删除这条帖子吗？',
          success: async (res) => {
            if (res.confirm) {
              try {
                await post('/community/delete', {
                  postId: postItem.id
                });
                
                // 从列表中移除
                const index = this.postList.findIndex(p => p.id === postItem.id);
                if (index > -1) {
                  this.postList.splice(index, 1);
                }
                
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
              } catch (error) {
                uni.showToast({
                  title: '删除失败',
                  icon: 'none'
                });
              }
            }
          }
        });
        break;
        
      case '举报':
        uni.navigateTo({
          url: `/pages/report/report?type=post&id=${postItem.id}`
        });
        break;
        
      case '不感兴趣':
        // 标记为不感兴趣，从推荐中移除
        const index = this.postList.findIndex(p => p.id === postItem.id);
        if (index > -1) {
          this.postList.splice(index, 1);
        }
        uni.showToast({
          title: '已标记为不感兴趣',
          icon: 'success'
        });
        break;
    }
  }
  
  /**
   * 跳转到搜索页面
   */
  goToSearch() {
    uni.navigateTo({
      url: '/pages/search/search?type=community'
    });
  }
  
  /**
   * 跳转到发布页面
   */
  goToPublish() {
    // 检查登录状态
    const token = uni.getStorageSync('token');
    const isGuest = uni.getStorageSync('isGuest');
    
    if (!token && !isGuest) {
      uni.showModal({
        title: '提示',
        content: '请先登录后再发布内容',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });
      return;
    }
    
    if (isGuest) {
      uni.showToast({
        title: '游客模式无法发布内容',
        icon: 'none'
      });
      return;
    }
    
    uni.navigateTo({
      url: '/pages/community/publish'
    });
  }
  
  /**
   * 获取模拟话题数据
   */
  getMockTopics(): Topic[] {
    return [
      { id: '1', name: '新手妈妈', postCount: 1250 },
      { id: '2', name: '辅食添加', postCount: 890 },
      { id: '3', name: '睡眠训练', postCount: 567 },
      { id: '4', name: '母乳喂养', postCount: 2100 },
      { id: '5', name: '早教启蒙', postCount: 780 }
    ];
  }
  
  /**
   * 获取模拟帖子数据
   */
  getMockPosts(): Post[] {
    return [
      {
        id: '1',
        authorId: '1',
        authorName: '新手妈妈小王',
        authorAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=young%20mother%20smiling&image_size=square',
        title: '宝宝第一次添加辅食的经历分享',
        content: '今天给6个月的宝宝第一次添加辅食，选择了铁强化米粉。宝宝一开始有点抗拒，但是慢慢就接受了。分享一些心得给大家...',
        images: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=baby%20first%20solid%20food&image_size=square',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=baby%20eating%20rice%20cereal&image_size=square'
        ],
        topics: [
          { id: '2', name: '辅食添加', postCount: 890 }
        ],
        likeCount: 45,
        commentCount: 12,
        shareCount: 8,
        isLiked: false,
        isFavorited: false,
        createdAt: '2024-01-15T10:30:00Z'
      },
      {
        id: '2',
        authorId: '2',
        authorName: '育儿达人李姐',
        authorAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=experienced%20mother&image_size=square',
        content: '分享一个超有效的哄睡方法！我家宝宝用了这个方法后，从原来的2小时哄睡缩短到15分钟，真的太神奇了！',
        video: {
          url: 'https://example.com/video1.mp4',
          cover: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=baby%20sleeping%20peacefully&image_size=landscape_16_9',
          duration: 180
        },
        topics: [
          { id: '3', name: '睡眠训练', postCount: 567 }
        ],
        likeCount: 128,
        commentCount: 34,
        shareCount: 22,
        isLiked: true,
        isFavorited: true,
        createdAt: '2024-01-14T15:20:00Z'
      },
      {
        id: '3',
        authorId: '3',
        authorName: '专家张医生',
        authorAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=professional%20pediatrician%20doctor&image_size=square',
        title: '关于宝宝发烧的几个误区',
        content: '很多家长在宝宝发烧时会犯一些常见的错误，今天来科普一下正确的处理方法。首先，不要一发烧就立即用退烧药...',
        images: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=baby%20fever%20thermometer&image_size=square'
        ],
        topics: [
          { id: '6', name: '宝宝健康', postCount: 1500 }
        ],
        likeCount: 89,
        commentCount: 56,
        shareCount: 45,
        isLiked: false,
        isFavorited: false,
        createdAt: '2024-01-13T09:15:00Z'
      }
    ];
  }
  

  
  /**
   * 显示评论弹窗
   */
  async showPostComments(post: Post) {
    this.selectedPost = post;
    this.showComments = true;
    await this.loadComments(post.id);
  }
  
  /**
   * 加载评论列表
   */
  async loadComments(postId: string) {
    if (this.commentLoading) return;
    
    this.commentLoading = true;
    
    try {
      const response = await get(`/community/posts/${postId}/comments`, {
        page: 1,
        pageSize: 50
      });
      
      this.commentList = response.data.comments || [];
    } catch (error) {
      console.error('加载评论失败:', error);
      // 使用模拟数据
      this.commentList = this.getMockComments();
    } finally {
      this.commentLoading = false;
    }
  }
  
  /**
   * 提交评论
   */
  async submitComment() {
    if (!this.commentText.trim()) {
      uni.showToast({
        title: '请输入评论内容',
        icon: 'none'
      });
      return;
    }
    
    if (!this.selectedPost) return;
    
    try {
      const response = await post('/community/comments', {
        postId: this.selectedPost.id,
        content: this.commentText.trim()
      });
      
      // 添加新评论到列表顶部
      const newComment: Comment = {
        id: response.data.id || Date.now().toString(),
        authorId: 'current_user',
        authorName: '我',
        authorAvatar: '/static/default-avatar.png',
        content: this.commentText.trim(),
        likeCount: 0,
        isLiked: false,
        createdAt: new Date().toISOString()
      };
      
      this.commentList.unshift(newComment);
      this.selectedPost.commentCount++;
      this.commentText = '';
      
      uni.showToast({
        title: '评论成功',
        icon: 'success'
      });
      
    } catch (error) {
      console.error('提交评论失败:', error);
      uni.showToast({
        title: '评论失败',
        icon: 'none'
      });
    }
  }
  
  /**
   * 点赞评论
   */
  async likeComment(comment: Comment) {
    try {
      await post('/community/comments/like', {
        commentId: comment.id,
        action: comment.isLiked ? 'unlike' : 'like'
      });
      
      comment.isLiked = !comment.isLiked;
      comment.likeCount += comment.isLiked ? 1 : -1;
      
    } catch (error) {
      console.error('点赞评论失败:', error);
      uni.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  }
  
  /**
   * 回复评论
   */
  replyComment(comment: Comment) {
    this.commentText = `@${comment.authorName} `;
  }
  
  /**
   * 举报帖子
   */
  async reportPost(postItem: Post) {
    this.showPostActions = false;
    
    uni.showModal({
      title: '举报帖子',
      content: '确定要举报这条帖子吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            await post('/community/report', {
              postId: postItem.id,
              reason: 'inappropriate_content'
            });
            
            uni.showToast({
              title: '举报成功',
              icon: 'success'
            });
          } catch (error) {
            console.error('举报失败:', error);
            uni.showToast({
              title: '举报失败',
              icon: 'none'
            });
          }
        }
      }
    });
  }
  
  /**
   * 屏蔽用户
   */
  async blockUser(postItem: Post) {
    this.showPostActions = false;
    
    uni.showModal({
      title: '屏蔽用户',
      content: `确定要屏蔽用户 ${postItem.authorName} 吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            await post('/community/block', {
              userId: postItem.authorId
            });
            
            // 从列表中移除该用户的所有帖子
            this.postList = this.postList.filter(p => p.authorId !== postItem.authorId);
            
            uni.showToast({
              title: '屏蔽成功',
              icon: 'success'
            });
          } catch (error) {
            console.error('屏蔽失败:', error);
            uni.showToast({
              title: '屏蔽失败',
              icon: 'none'
            });
          }
        }
      }
    });
  }
  
  /**
   * 复制链接
   */
  copyLink(postItem: Post) {
    this.showPostActions = false;
    
    const link = `https://your-domain.com/community/post/${postItem.id}`;
    
    // #ifdef H5
    if (navigator.clipboard) {
      navigator.clipboard.writeText(link).then(() => {
        uni.showToast({
          title: '链接已复制',
          icon: 'success'
        });
      });
    }
    // #endif
    
    // #ifdef MP-WEIXIN || APP-PLUS
    uni.setClipboardData({
      data: link,
      success: () => {
        uni.showToast({
          title: '链接已复制',
          icon: 'success'
        });
      }
    });
    // #endif
  }
  
  /**
   * 获取模拟评论数据
   */
  getMockComments(): Comment[] {
    return [
      {
        id: '1',
        authorId: '1',
        authorName: '热心妈妈',
        authorAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=kind%20mother&image_size=square',
        content: '我家宝宝也是这样，刚开始很抗拒，后来慢慢就好了。建议可以先让宝宝闻一闻，熟悉味道。',
        likeCount: 5,
        isLiked: false,
        createdAt: '2024-01-15T11:00:00Z'
      },
      {
        id: '2',
        authorId: '2',
        authorName: '新手爸爸',
        authorAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=young%20father&image_size=square',
        content: '请问米粉要调多稠呢？我家宝宝总是吐出来。',
        likeCount: 2,
        isLiked: true,
        createdAt: '2024-01-15T11:30:00Z'
      }
    ];
  }
}
</script>

<style lang="scss" scoped>
.community-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  position: relative;
}

.community-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: white;
  border-bottom: 1rpx solid #f0f0f0;
  
  .header-tabs {
    display: flex;
    
    .tab-item {
      padding: 15rpx 25rpx;
      margin-right: 10rpx;
      
      .tab-text {
        font-size: 28rpx;
        color: #666;
        transition: color 0.3s;
      }
      
      &.active {
        position: relative;
        
        .tab-text {
          color: #007aff;
          font-weight: 600;
        }
        
        &::after {
          content: '';
          position: absolute;
          bottom: -20rpx;
          left: 50%;
          transform: translateX(-50%);
          width: 40rpx;
          height: 4rpx;
          background-color: #007aff;
          border-radius: 2rpx;
        }
      }
    }
  }
  
  .header-actions {
    padding: 10rpx;
  }
}

.topic-recommend {
  background-color: white;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  .topic-scroll {
    white-space: nowrap;
  }
  
  .topic-list {
    display: flex;
    padding: 0 30rpx;
    
    .topic-item {
      flex-shrink: 0;
      padding: 20rpx 30rpx;
      margin-right: 20rpx;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border-radius: 20rpx;
      text-align: center;
      
      .topic-tag {
        display: block;
        font-size: 28rpx;
        font-weight: 600;
        color: white;
        margin-bottom: 8rpx;
      }
      
      .topic-count {
        font-size: 22rpx;
        color: rgba(255, 255, 255, 0.8);
      }
    }
  }
}

.post-list {
  flex: 1;
  padding: 20rpx 0;
}

.post-item {
  background-color: white;
  margin-bottom: 20rpx;
  padding: 30rpx;
  
  .post-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .user-info {
      display: flex;
      align-items: center;
      
      .user-details {
        margin-left: 15rpx;
        
        .user-name {
          display: block;
          font-size: 28rpx;
          font-weight: 600;
          color: #333;
          margin-bottom: 5rpx;
        }
        
        .post-time {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
  }
  
  .post-content {
    margin-bottom: 25rpx;
    
    .post-title {
      display: block;
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
      line-height: 1.4;
      margin-bottom: 15rpx;
    }
    
    .post-text {
      font-size: 28rpx;
      color: #333;
      line-height: 1.6;
      margin-bottom: 15rpx;
    }
    
    .post-topics {
      margin-bottom: 15rpx;
      
      .topic-tag {
        display: inline-block;
        padding: 8rpx 16rpx;
        margin-right: 15rpx;
        background-color: #f0f8ff;
        color: #007aff;
        font-size: 24rpx;
        border-radius: 12rpx;
      }
    }
    
    .post-images {
      margin-bottom: 15rpx;
      
      .image-grid {
        display: grid;
        gap: 10rpx;
        border-radius: 12rpx;
        overflow: hidden;
        
        &.grid-1 {
          grid-template-columns: 1fr;
          
          .post-image {
            height: 400rpx;
          }
        }
        
        &.grid-2 {
          grid-template-columns: 1fr 1fr;
          
          .post-image {
            height: 200rpx;
          }
        }
        
        &.grid-3 {
          grid-template-columns: 1fr 1fr 1fr;
          
          .post-image {
            height: 150rpx;
          }
        }
        
        &.grid-4 {
          grid-template-columns: 1fr 1fr;
          
          .post-image {
            height: 150rpx;
          }
        }
        
        &.grid-5,
        &.grid-6,
        &.grid-7,
        &.grid-8,
        &.grid-9 {
          grid-template-columns: 1fr 1fr 1fr;
          
          .post-image {
            height: 120rpx;
          }
        }
        
        .post-image {
          width: 100%;
          border-radius: 8rpx;
        }
        
        .more-images {
          position: relative;
          background-color: rgba(0, 0, 0, 0.6);
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 8rpx;
          
          .more-text {
            font-size: 24rpx;
            color: white;
            font-weight: 600;
          }
        }
      }
    }
    
    .post-video {
      position: relative;
      border-radius: 12rpx;
      overflow: hidden;
      
      .video-cover {
        width: 100%;
        height: 400rpx;
      }
      
      .video-play-btn {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 100rpx;
        height: 100rpx;
        background-color: rgba(0, 0, 0, 0.6);
        border-radius: 50rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      
      .video-duration {
        position: absolute;
        bottom: 15rpx;
        right: 15rpx;
        padding: 8rpx 12rpx;
        background-color: rgba(0, 0, 0, 0.7);
        border-radius: 8rpx;
        
        .duration-text {
          font-size: 22rpx;
          color: white;
        }
      }
    }
  }
  
  .post-stats {
    display: flex;
    justify-content: space-around;
    padding-top: 20rpx;
    border-top: 1rpx solid #f0f0f0;
    
    .stat-item {
      display: flex;
      align-items: center;
      padding: 10rpx 20rpx;
      
      .stat-text {
        margin-left: 8rpx;
        font-size: 24rpx;
        color: #666;
        transition: color 0.3s;
        
        &.liked {
          color: #ff4757;
        }
        
        &.favorited {
          color: #ffd700;
        }
      }
    }
  }
}

.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
  
  .loading-text {
    margin-left: 15rpx;
    font-size: 26rpx;
    color: #999;
  }
}

.no-more {
  text-align: center;
  padding: 40rpx;
  
  .no-more-text {
    font-size: 26rpx;
    color: #999;
  }
}

.publish-btn {
  position: fixed;
  bottom: 120rpx;
  right: 30rpx;
  width: 100rpx;
  height: 100rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.4);
  z-index: 100;
}

// 帖子操作弹窗
.post-actions-popup {
  padding: 30rpx;
  background-color: #fff;
  
  .action-header {
    text-align: center;
    margin-bottom: 30rpx;
    
    .action-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .action-list {
    .action-item {
      display: flex;
      align-items: center;
      padding: 30rpx 0;
      border-bottom: 1rpx solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .action-text {
        margin-left: 20rpx;
        font-size: 28rpx;
        color: #333;
      }
    }
  }
}

// 评论弹窗
.comments-popup {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fff;
  
  .comments-header {
    padding: 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    .comments-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .comments-list {
    flex: 1;
    padding: 0 30rpx;
    
    .comment-item {
      display: flex;
      padding: 30rpx 0;
      border-bottom: 1rpx solid #f8f9fa;
      
      .comment-avatar {
        width: 60rpx;
        height: 60rpx;
        border-radius: 30rpx;
        margin-right: 20rpx;
      }
      
      .comment-content {
        flex: 1;
        
        .comment-author {
          font-size: 26rpx;
          color: #666;
          margin-bottom: 10rpx;
        }
        
        .comment-text {
          font-size: 28rpx;
          color: #333;
          line-height: 1.5;
          margin-bottom: 15rpx;
        }
        
        .comment-meta {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .comment-time {
            font-size: 24rpx;
            color: #999;
          }
          
          .comment-actions {
            display: flex;
            gap: 30rpx;
            
            .comment-action {
              display: flex;
              align-items: center;
              gap: 8rpx;
              
              .action-count,
              .action-text {
                font-size: 24rpx;
                color: #999;
              }
            }
          }
        }
      }
    }
  }
  
  .comment-input-bar {
    display: flex;
    align-items: center;
    padding: 20rpx 30rpx;
    border-top: 1rpx solid #f0f0f0;
    background-color: #fff;
    
    .comment-input {
      flex: 1;
      height: 60rpx;
      padding: 0 20rpx;
      background-color: #f8f9fa;
      border-radius: 30rpx;
      font-size: 28rpx;
      border: none;
    }
    
    .send-btn {
      margin-left: 20rpx;
      padding: 15rpx 30rpx;
      background-color: #1890ff;
      color: #fff;
      border-radius: 30rpx;
      font-size: 26rpx;
      border: none;
    }
  }
}
</style>